package com.example.color_test.controller;


import com.example.color_test.entity.Img;
import com.example.color_test.entity.Page;
import com.example.color_test.mapper.ImgMapper;
import com.example.color_test.utils.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Api(tags = "图片模块")
@RestController
@RequestMapping("/img")
public class ImgController {

    @Resource
    ImgMapper imgMapper;

    //上传图片
    @ApiOperation(value = "上传图片")
    @PostMapping(value = "/imageUpload")
    public Object imageUpload(@RequestParam(required = true) MultipartFile file,@RequestParam(required = false) String keyId) throws IOException {

        String filePath ="";
        //上传图片限制大小
        Long len = file.getSize();
        boolean isBig=  FilePath.checkFileSize(len,4);
        if(!isBig){
            return ResultCode.ERRO.Result("文件超出4M，请压缩后重试");
        }
        try {
            //上传实际方法
            if(file.getSize()!=0) {
                filePath = FilePath.uploadFile(file);
            }}
        //上传失败提示
        catch (IOException e) {
            return ResultCode.ERRO.Result("上传失败");
        }
        Img img = new Img();
        img.setPath(filePath);
        img.setTime(String.valueOf(new Date().getTime()));
        img.setKeyId(UUIDUtils.getUUID());
        if(keyId!=null&& !keyId.equals("")){
            img.setKeyId(keyId);
        }
        int state = imgMapper.insert(img);
        if(state<=0){
            return ResultCode.ERRO.Result("上传失败");
        }
        //上传成功
        return ResultCode.SUCCSSES.Result("上传成功",img);
    }

    @ApiOperation(value = "删除图片")
    @DeleteMapping("/deleteImg/{id}")
    public Object deleteImg(@PathVariable(required = true,value = "id") int id){
        Img img = imgMapper.load(id);
        if(img.getUseState()==1){
            return ResultCode.ERRO.Result("图片已被使用，无法删除");
        }
        String _selfPath = FilePath.getAllImgPath(img.getPath());
        System.out.println("开始执行，图片路径为"+_selfPath);
        File file = new File(_selfPath);
        //判断文件是否存在
        if (file.exists()){
            System.out.println("图片存在，可执行删除操作");
            boolean flag = false;
            flag = file.delete();
            if (flag){
                System.out.println("成功删除图片"+file.getName());
                imgMapper.delete(id);
                return ResultCode.SUCCSSES.Result("删除图片成功");
            }else {
                System.out.println("删除失败");
                return ResultCode.ERRO.Result("删除失败");
            }
        }else {
            System.out.println("图片不存在，终止操作");
            return ResultCode.ERRO.Result("图片不存在，终止操作");
        }
    }

    @ApiOperation(value = "删除图库图片")
    @PostMapping("/deleteHistoryImg")
    public Object deleteHistoryImg(@RequestBody  List<Img> imgs){
        try{
            for(Img img : imgs){
                String _selfPath = FilePath.getAllImgPath(img.getPath());
                System.out.println("开始执行，图片路径为"+_selfPath);
                File file = new File(_selfPath);
                //判断文件是否存在
                if (file.exists()){
                    System.out.println("图片存在，可执行删除操作");
                    boolean flag = false;
                    flag = file.delete();
                    if (flag){
                        System.out.println("成功删除图片"+file.getName());
                        imgMapper.delete(img.getId());
                    }else {
                        System.out.println("删除失败");
                        return ResultCode.ERRO.Result("删除失败");
                    }
                }else {
                    System.out.println("图片不存在，终止操作");
                    return ResultCode.ERRO.Result("图片不存在，终止操作");
                }
            }
            return ResultCode.SUCCSSES.Result("删除图片成功");
        }catch (Exception e){
            return ResultCode.ERRO.Result("删除图片失败，出现未知错误");
        }

    }

    @ApiOperation(value = "查询历史图片（分页）")
    @GetMapping("/getHistoryImages")
    public Object getHistoryImages(@RequestParam(required = true,value = "page") int page,
                                   @RequestParam(required = true,value = "size") int size,
                                   @RequestParam(required = true,value = "firstId") int firstId){
        System.out.println(page);
        System.out.println(size);
        Page result = new Page();
        PageHelper.startPage(page,size);
        List<Img> imgs = new ArrayList<>();
        if(firstId>0){
            imgs = imgMapper.selectImagesByLastId(firstId);
        }else {
            imgs = imgMapper.selectImages();
        }
        PageInfo<Img> pageInfo = new PageInfo<Img>(imgs);
        result.setPage(pageInfo.getPageNum());
        result.setSize(pageInfo.getPageSize());
        result.setPages(pageInfo.getPages());
        result.setTotals(pageInfo.getTotal());
        result.setDataList(imgs);
        return ResultCode.SUCCSSES.Result("查询成功",result);
    }




}
